package com.kaifamiao.define;

import com.kaifamiao.util.JdbcHelper;
import com.kaifamiao.util.RowHandler;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 第二种定义Servlet类的方式:
 * 通过继承 javax.servlet.GenericServlet 类 来定义一个 Servlet 类
 */
public class UniversalServlet extends GenericServlet {

    @Override
    public void service(ServletRequest req, ServletResponse resp)
            throws ServletException, IOException {
        // 查询数据库得到 List 集合
        JdbcHelper helper = JdbcHelper.getInstance();

        final String sql = "SELECT empno , ename , job , sal FROM emp" ;

        final RowHandler< Map<String,Object> > handler = new RowHandler<>() {
            @Override
            public Map<String, Object> handle(ResultSet rs) throws SQLException {
                Map<String, Object> map = new HashMap<>();
                int empno = rs.getInt( "empno" );
                map.put( "empno" , empno );
                String ename = rs.getString( "ename" );
                map.put( "ename" , ename );
                String job = rs.getString( "job" );
                map.put( "job" , job );
                float sal = rs.getFloat( "sal" );
                map.put( "sal" , sal );
                return map;
            }
        };

        List< Map<String,Object> > list = helper.query( sql , handler );

        helper.release();

        // 设置响应头
        resp.setContentType( "text/html" );
        // 获得可以向客户端输出数据的字符打印流
        PrintWriter out = resp.getWriter();

        out.println( "<table border=\"1\" align=\"center\">" );

        out.println( "<tr>" );
        out.println( "<th>工号</th>" );
        out.println( "<th>姓名</th>" );
        out.println( "<th>岗位</th>" );
        out.println( "<th>薪水</th>" );
        out.println( "</tr>" );

        for ( Map<String,Object> map : list ) {
            out.println( "<tr>" );
            Object empno = map.get( "empno" );
            out.println( "<td>" + empno + "</td>" );
            Object ename = map.get( "ename" );
            out.println( "<td>" + ename + "</td>" );
            Object job = map.get( "job" );
            out.println( "<td>" + job + "</td>" );
            Object sal = map.get( "sal" );
            out.println( "<td>" + sal + "</td>" );
            out.println( "</tr>" );
        }

        out.println( "</table>");

    }

}
